package com.spring.security.web.service.impl;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.api.AliyunClient;
import com.aliyun.api.DefaultAliyunClient;
import com.aliyun.api.domain.Job;
import com.aliyun.api.domain.OSSFile;
import com.aliyun.api.domain.SnapshotJob;
import com.aliyun.api.mts.mts20140618.request.QueryJobListRequest;
import com.aliyun.api.mts.mts20140618.request.QuerySnapshotJobListRequest;
import com.aliyun.api.mts.mts20140618.request.SubmitSnapshotJobRequest;
import com.aliyun.api.mts.mts20140618.response.QueryJobListResponse;
import com.aliyun.api.mts.mts20140618.response.QuerySnapshotJobListResponse;
import com.aliyun.api.mts.mts20140618.response.SubmitSnapshotJobResponse;
import com.spera.aliyunContent.AliyunContent;
import com.spera.aliyunUtil.CreateOSSClient;
import com.spera.aliyunUtil.OSSFileDO;
import com.spera.aliyunUtil.SperaMTSUtil;
import com.spring.common.web.service.CommonService;
import com.spring.iosservice.web.dao.IosQuestMapper;
import com.spring.iosservice.web.model.CourseMtsInfo;
import com.spring.iosservice.web.model.MtsLog;
import com.spring.iosservice.web.service.IosQuestService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.UDate;
import com.spring.security.web.service.MtsService;
import com.taobao.api.ApiException;

@Service
public class MtsServiceImpl implements MtsService{
	@Resource
	private IosQuestMapper IosQuestMapper;
	@Resource
	private MongoTemplate mongoService;
	@Resource
	private CommonService commonService;
	@Resource
	private IosQuestService iosQuestService;	
	
	private AliyunClient aliyunClient = new DefaultAliyunClient(AliyunContent.MTS_SERVER_URL, AliyunContent.accessKeyId, AliyunContent.accessKeySecret);
	
	public void checkMts(Message message){
		CourseMtsInfo one = new CourseMtsInfo();
		if(message instanceof ObjectMessage){
            ObjectMessage objectMessage=(ObjectMessage) message;
	        try {
	        	one=(CourseMtsInfo) objectMessage.getObject();
	        } catch (JMSException e) {
	            e.printStackTrace();
	        }
		}
		System.out.println("检测---->"+one.getCourseVideosId());
		try{
			//文件名
			String encodedObjectName = URLEncoder.encode(one.getOssFilePath(), "utf-8");
			//转码作业还没开始
			OSSFileDO inputFile = new OSSFileDO(AliyunContent.location,AliyunContent.inputBucket,encodedObjectName);
			
			//截图作业
			snapshotJobFlow(inputFile,one,encodedObjectName,one.getImgae_uuid());
			
			//获取通道
			SperaMTSUtil.getInstance().systemTemplateJobFlow(inputFile);
			
			String transcodeJobId = SperaMTSUtil.getInstance().submitTranscodeJob(inputFile, AliyunContent.transcodeTemplateId);//templateId
			//转码作业
			transcodeJobFlow(transcodeJobId,one,encodedObjectName,one.getImgae_uuid());
			
		}catch(Exception e){
			e.printStackTrace();
			//错误日志记录
			MtsLog msg = new MtsLog();
			msg.setCourseVideosId(one.getCourseVideosId());
			msg.setTranscodeJobId(one.getTranscodeJobId());
			msg.setOssFilePath(one.getOssFilePath());
			msg.setVideoUrl(one.getVideoUrl());
			msg.setModelName(one.getModelName());
			msg.setToken(one.getToken());
			msg.setEtag(one.getEtag());
			msg.setErrorMsg(e.getMessage().substring(0, e.getMessage().length()>100?100:e.getMessage().length()));
			mongoService.insert(msg);
		}
	}
	
	
	//转码流程
    private void transcodeJobFlow(String transcodeJobId,CourseMtsInfo one,String encodedObjectName,String image_id) {
//    	Query q = new Query(Criteria.where("courseVideosId").is(one.getCourseVideosId()));
    	//模版分析作业
//		String templateId = SperaMTSUtil.getInstance().systemTemplateJobFlow(inputFile);
		//提交转码作业开始转码
//		String transcodeJobId = SperaMTSUtil.getInstance().submitTranscodeJob(inputFile, AliyunContent.transcodeTemplateId);//templateId
//		mongoService.updateFirst(q, Update.update("transcodeJobId", transcodeJobId), CourseMtsInfo.class);
		//检测转码作业是否完成
		Job transcodeJob = checkTranscodeJobComplete(transcodeJobId);
		if(transcodeJob!=null){
			OSSFile outputFile  = transcodeJob.getOutput().getOutputFile();
//			String outputFileOSSUrl = outputFile.getLocation();
	        String outputFileOSSUrl = "http://" + outputFile.getBucket() + ".oss-cn-hangzhou.aliyuncs.com/" + outputFile.getObject();
			int i = 0;
			//获取Object Metadata
//			OSSObject object = CreateOSSClient.getInstance().getOSSClient().getObject(outputFile.getBucket(), outputFile.getObject());
//			ObjectMetadata metadata = object.getObjectMetadata();
//			long sd = metadata.getContentLength();
//			
//			Date dat=new Date(sd);  
//            GregorianCalendar gc = new GregorianCalendar();   
//            gc.setTime(dat);  
//            java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("hh:mm:ss");  
//            String sb=format.format(gc.getTime());  
//            System.out.println(sb);  
			
			if("common".equalsIgnoreCase(one.getModelName())){//oss基础接口
				Map<String,Object> im = new HashMap<String,Object>();
				im.put("id", one.getCourseVideosId());
				im.put("image_id", image_id);
				im.put("bucket", outputFile.getBucket());
				im.put("url", outputFileOSSUrl);
				im.put("etag", one.getEtag());//video mts  无etag
				im.put("key", outputFile.getObject());
				im.put("token", one.getToken());
				im.put("file_type", "video");
				im.put("c_user_id", one.getC_user_id());
				i = commonService.updateVideosFile(im);				
	
			}
			if("coursevideo".equalsIgnoreCase(one.getModelName())){//课程视频
				Map<String, Object> s = new HashMap<String, Object>();
				s.put("id", one.getCourseVideosId());
				s.put("status", "1");
				s.put("video_src", outputFileOSSUrl);
				i = IosQuestMapper.updateVideoPhoto(s);
				
				iosQuestService.createIOSVideoJournal(one.getCourseVideosId(), outputFile.getObject(), one.getBabyIDs());
				
			}
			if(i==1){
//				Query q = new Query(Criteria.where("transcodeJobId").is(one.getTranscodeJobId()));
//				mongoService.remove(q, CourseMtsInfo.class);
				//删除未压缩过的视频文件
				CreateOSSClient.getInstance().getOSSClient().deleteObject(AliyunContent.inputBucket, encodedObjectName);
			}
		}
    }
	
	//转码检测
	private Job checkTranscodeJobComplete(String transcodeJobId) {
		QueryJobListRequest request = new QueryJobListRequest();
        request.setJobIds(transcodeJobId);
        try {
            while (true) {
                QueryJobListResponse response = aliyunClient.execute(request);
                if(!response.isSuccess()) {
                    throw new RuntimeException("QueryJobListRequest failed");
            	}
                Job transcodeJob = response.getJobList().get(0);
                String status = transcodeJob.getState();
                if ("TranscodeFail".equals(status)) {
                    throw new RuntimeException("transcodeJob state Failed");
                }
                if ("TranscodeSuccess".equals(status)) {
                    return transcodeJob;
                }
                Thread.sleep(5 * 1000);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
	}
	
	//截图流程
    private void snapshotJobFlow(OSSFileDO inputFile,CourseMtsInfo one,String encodedObjectName,String image_id) {
//    	String image_id = ApplicationUtils.randomUUID();
    	try{
    		String snapshotJobId = submitSnapshotJob(inputFile);
            SnapshotJob job = waitSnapshotComplete(snapshotJobId);
            OSSFile outputFile  = job.getSnapshotConfig().getOutputFile();
            String outputFileOSSUrl = "http://" + outputFile.getBucket() + ".img-cn-hangzhou.aliyuncs.com/" + outputFile.getObject();
            if("common".equalsIgnoreCase(one.getModelName())){//oss基础接口
            	Map<String,Object> im = new HashMap<String,Object>();
         		im.put("id", image_id);
         		im.put("bucket", outputFile.getBucket());
         		im.put("url", outputFileOSSUrl);
         		im.put("etag", one.getEtag());//video mts  无etag
         		im.put("key", outputFile.getObject());
         		im.put("token", one.getToken());
         		im.put("file_type", "image");
         		im.put("c_user_id", one.getC_user_id());
         		commonService.updateOssFile(im);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
//        System.out.println("snapshot success, the target file url is " + outputFileOSSUrl);
    }
	
    //提交截图作业
    private String submitSnapshotJob(OSSFileDO inputFile){
        OSSFileDO outputSnapshotFile = new OSSFileDO();
        outputSnapshotFile.setBucket(AliyunContent.outputBucket);
        outputSnapshotFile.setLocation("oss-cn-hangzhou");
        outputSnapshotFile.setObject("spera-video-cover/"+UDate.getDate()+"/" + ApplicationUtils.randomUUID() + ".jpg");

        JSONObject jobConfig = new JSONObject();
        jobConfig.put("OutputFile", outputSnapshotFile.toJson());
        jobConfig.put("Time", 1000L);   //snapshot time by ms

        SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();
        request.setSnapshotConfig(jobConfig.toJSONString());
        request.setInput(inputFile.toJsonString());

        try {
            SubmitSnapshotJobResponse response = aliyunClient.execute(request);
            if(!response.isSuccess()) {
                throw new RuntimeException("SubmitSnapshotJobRequest failed");
        	}
            return response.getSnapshotJob().getId();
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
    }

    //检测截图作业
    private SnapshotJob waitSnapshotComplete(String snapshotJobId){
        QuerySnapshotJobListRequest request = new QuerySnapshotJobListRequest();
        request.setSnapshotJobIds(snapshotJobId);
        try {
            while (true){
                QuerySnapshotJobListResponse response = aliyunClient.execute(request);
                if(!response.isSuccess()) {
                    throw new RuntimeException("QuerySnapshotJobListRequest failed");
            	}
                SnapshotJob job = response.getSnapshotJobList().get(0);
                String status = job.getState();
                if ("Fail".equals(status)) {
                    throw new RuntimeException("QuerySnapshotJobListRequest Failed");
                }
                if ("Success".equals(status)) {
                    return job;
                }
                Thread.sleep(2 * 1000);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
